package com.smartlbs.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.omg.PortableServer.POA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.smartlbs.baseframe.utils.ConfigFileUtils;
import com.smartlbs.baseframe.utils.HttpClientUtil;
import com.smartlbs.baseframe.utils.WeChatUtils;
import com.smartlbs.baseframe.web.ResponseInfo;
import com.smartlbs.dto.UserBasicDto;
import com.smartlbs.entity.SysUser;
import com.smartlbs.entity.UserBasic;
import com.smartlbs.entity.YunXin;
import com.smartlbs.service.IUserBasicService;
import com.smartlbs.util.DESUtil;
import com.smartlbs.util.StringUtil;
import com.smartlbs.vo.UserBasicVo;


/**
 * 用户基本信息控制层实现类
 * 
 * 
 *
 */
@Controller
@RequestMapping("user/basic")
public class UserBasicController {
	
	@Autowired
	private IUserBasicService userBasicService;
	
	/**
	 * 用户认证登录
	 * 
	 * 
	 * 
	 * @param request
	 * @param code
	 * @return
	 */
	@RequestMapping("authLogin")
	@ResponseBody
	public ResponseInfo authLogin(HttpServletRequest request, String code, Integer os){
		//
		int result = 0;
		String message = "";
		Object data = null;
		
		if(StringUtil.containEmpty(code)){
			message = "code不能为空";
		}else{
			try {
				UserBasic userBasic = userBasicService.authLogin(code,os==null?2:os);
				//
				UserBasicVo userBasicVo = new UserBasicVo();
				//
				BeanUtils.copyProperties(userBasicVo, userBasic);
				//
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//
				String keyword = userBasic.getUserId()+"*#&"+userBasic.getOpenId()+"*#&"+format.format(userBasic.getLastLogin());
				userBasicVo.setToken(DESUtil.encryptString("mot_user_token", keyword));
				System.out.println(userBasicVo.getToken());
				result = 1;
				message = "用户登录认证成功";
				data = userBasicVo;
			} catch (Exception e) {
				message = "用户登录认证失败";
				e.printStackTrace();
			}
		}
		
		/*
		 * 返回值信息
		 */
		ResponseInfo responseInfo = new ResponseInfo();
		
		responseInfo.setResult(result);
		responseInfo.setMessage(message);
		responseInfo.setData(data);
		
		return responseInfo;
	}

	/**
	 * 获取用户信息
	 * 
	 * 
	 * 
	 * @param request
	 * @param code
	 * @return
	 */
	@RequestMapping("get")
	@ResponseBody
	public ResponseInfo get(HttpServletRequest request, Long userId){
		//
		int result = 0;
		String message = "";
		Object data = null;
		
		if(userId == null){
			//
			UserBasic userBasic = (UserBasic)request.getAttribute("currentUser");
			
			//
			userId = userBasic.getUserId();
		}

		try {
			UserBasicVo userBasicVo = userBasicService.getUserInfo(userId);
			result = 1;
			message = "用户信息获取成功";
			data = userBasicVo;
		} catch (Exception e) {
			message = "用户信息获取失败";
			e.printStackTrace();
		}
		
		/*
		 * 返回值信息
		 */
		ResponseInfo responseInfo = new ResponseInfo();
		
		responseInfo.setResult(result);
		responseInfo.setMessage(message);
		responseInfo.setData(data);
		
		return responseInfo;
	}
	
	/**
	 * 获取用户信息
	 * 
	 * 
	 * 
	 * @param request
	 * @param code
	 * @return
	 */
	@RequestMapping("find")
	@ResponseBody
	public ResponseInfo find(HttpServletRequest request, Integer pageNum, Integer pageSize, UserBasicDto userBasicDto){
		//
		int result = 0;
		String message = "";
		Object data = null;
		
		//
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		
		try {
			data = userBasicService.find(pageNum, pageSize, userBasicDto);
			
			result = 1;
			message = "数据获取成功";
		} catch (Exception e) {
			result = 0;
			message = "数据获取失败";
			e.printStackTrace();
		}
		
		/*
		 * 返回值信息
		 */
		ResponseInfo responseInfo = new ResponseInfo();
		
		responseInfo.setResult(result);
		responseInfo.setMessage(message);
		responseInfo.setData(data);
		
		return responseInfo;
	}

	/**
	 * 统一下单
	 * 
	 * 
	 * 
	 * @param request
	 * @param code
	 * @return
	 */
	@RequestMapping("unifiedOrder")
	@ResponseBody
	public ResponseInfo unifiedOrder(HttpServletRequest request, Double points,Integer os){
		//
		int result = 0;
		String message = "";
		Object data = null;
		
		try {
			//
			UserBasic userBasic = (UserBasic)request.getAttribute("currentUser");

			data = WeChatUtils.unifiedOrder(userBasic.getOpenId(), userBasic.getUserId(), points, os==null?2:os);
			System.out.println(data);
			result = 1;
			message = "下单成功";
		} catch (Exception e) {
			result = 0;
			message = "下单失败";
			e.printStackTrace();
		}
		
		/*
		 * 返回值信息
		 */
		ResponseInfo responseInfo = new ResponseInfo();
		
		responseInfo.setResult(result);
		responseInfo.setMessage(message);
		responseInfo.setData(data);
		
		return responseInfo;
	}
	
	/**
	 * 执行回调
	 * 
	 * 
	 * 
	 * @param request
	 * @throws IOException 
	 */
	@RequestMapping("callback")
	public String callBack(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		try {
			synchronized (this) {
				String message = "";
				String str = "";
				//
				BufferedReader br=request.getReader();
				while ((str = br.readLine()) != null) {
					message+=str;
				}
				//关闭流
				br.close();
				//
				System.out.println("message============="+message);
				//处理回调
				userBasicService.callBack(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			PrintWriter out=response.getWriter();
			out.print("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			out.close();
			return null;
		}
		
	}
	
	/**
	 * 变更积分
	 * 
	 * 
	 * 
	 * @param request
	 * @param code
	 * @return
	 */
	@RequestMapping("changePoints")
	@ResponseBody
	public ResponseInfo changePoints(HttpServletRequest request, Long userId, Double points){
		//
		int result = 0;
		String message = "";
		Object data = null;
		
		try {
			//后台登陆人
			SysUser user= (SysUser) request.getSession().getAttribute("sysUser");
			data = userBasicService.updatePoints(user, userId, points);
			
			result = 1;
			message = "变更成功";
		} catch (Exception e) {
			result = 0;
			message = "变更失败";
			e.printStackTrace();
		}
		
		/*
		 * 返回值信息
		 */
		ResponseInfo responseInfo = new ResponseInfo();
		responseInfo.setResult(result);
		responseInfo.setMessage(message);
		responseInfo.setData(data);
		return responseInfo;
	}
	/**	获取短信验证码
	 * @param request
	 * @param phoneNum
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getSmscode")
	public ResponseInfo getSmsCode(HttpServletRequest request,String phone){
		ResponseInfo info = new ResponseInfo();
		int result = 0;
		String message = "";
		Object data = null;
		try {
		Random random = new Random();
		
		int code = random.nextInt(10000);
		
		YunXin yunXin = new YunXin();
		yunXin.setTo(phone);
		yunXin.setAppId(ConfigFileUtils.getPropertyString("phone_appId"));
		yunXin.setTemplateId(ConfigFileUtils.getPropertyString("phone_TemplateId"));
		List<String> datas=new ArrayList<String>();
		datas.add(String.valueOf(code));
		datas.add("200");
		yunXin.setDatas(datas);
		String body = JSON.toJSONString(yunXin);
		String sendCode = HttpClientUtil.sendCode(body);
		if(sendCode.equals("000000")){
			message="获取成功";
			result=1;
			data=code;
			//将code存到用户信息中
			UserBasic userBasic = (UserBasic)request.getAttribute("currentUser");

			userBasic.setLoginCode(String.valueOf(code));
			//更新用户信息
			 userBasicService.update(userBasic);
		}
		
		} catch (Exception e) {
			e.printStackTrace();
			 result = 0;
			 message = "获取失败";
		}
		info.setData(data);
		info.setMessage(message);
		info.setResult(result);
		return info;
	}
	/**	绑定手机号
	 * @param request
	 * @param phone
	 * @return
	 */
	@ResponseBody
	@RequestMapping("bindphone")
	public ResponseInfo bindPhone(HttpServletRequest request,String phone){
		ResponseInfo info = new ResponseInfo();
		int result = 0;
		String message = "";
		Object data = null;
		
		try {
			UserBasic userBasic = (UserBasic)request.getAttribute("currentUser");
			userBasic.setPhone(phone);
			
			//更新用户信息
			userBasicService.update(userBasic);

		} catch (Exception e) {
			e.printStackTrace();
			 result = 0;
			 message = "绑定失败";
		}
		
		info.setData(data);
		info.setMessage(message);
		info.setResult(result);
		return info;
	}
	
	/**	验证短信码
	 * @param request
	 * @param code
	 * @return
	 */
	@ResponseBody
	@RequestMapping("volidateCode")
	public ResponseInfo volidateCode(HttpServletRequest request,String code){
		ResponseInfo info = new ResponseInfo();
		int result = 0;
		String message = "";
		Object data = null;
		
		try {
			UserBasic userBasic = (UserBasic)request.getAttribute("currentUser");
			
			UserBasicVo userInfo = userBasicService.getUserInfo(userBasic.getUserId());
			if(code.equals(userInfo.getLoginCode())){
				result=1;
				message="验证成功";
			}else{
				result=-1;
				message="验证码错误";
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result=-1;
			message="验证码错误";
		}
		info.setData(data);
		info.setMessage(message);
		info.setResult(result);
		return info;
	}
}